package checkers.server.logic.classes.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import checkers.common.logic.classes.NoCloseInputStream;
import checkers.common.logic.commands.Command;
import checkers.server.logic.classes.Logger;

public class NetLayer {
	
	private Logger log;
	private WorkQueue work;
	private int port;
	private CommandsSerializer serializer;
	
	public NetLayer(Logger log, int port) throws Exception {
		this.log = log;
		this.port = port;
		work = new WorkQueue();
		serializer = new CommandsSerializer("checkers.common.logic.commands");
	}

	public void startListening() throws IOException {
		log.addMessage("Listening starts!");
		ServerSocket servers = new ServerSocket(port);
		log.addMessage("Waiting for a client...");
		while (true) {
			Socket socket = servers.accept();
		    log.addMessage("Connected client from: " + socket.getInetAddress() + 
		    		":" + socket.getPort());
		    work.execute(new ListenToClient(socket));
		}
	}
	
	public void sendCommand(Command command, Socket toClient) throws Exception {
		serializer.writeCommandToStream(toClient.getOutputStream(), command);
		toClient.shutdownOutput();
		log.addMessage("Command sent: " + command.getClass().toString());
	}
	
	public Command startReceivingCommand(Socket fromClient) throws Exception {;
		NoCloseInputStream input = new NoCloseInputStream(fromClient.getInputStream());
		Command command = (Command)serializer.getCommandFromStream(input);
		log.addMessage("Command received: "  + command.getClass().toString());
		return command;
	}
	
}
